<template>
	<div class="app-container">
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" @click="handlPin"
					v-hasPermi="['usecar:details:edit']" v-if="detailsList.length">内部拼车
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
					v-hasPermi="['usecar:details:add']">内部约车
				</el-button>
			</el-col>
			<right-toolbar :search="false" @queryTable="getList"></right-toolbar>
		</el-row>
		
		<el-empty description="暂无可拼车行程" v-if="queryParams.pageNum == 1 && detailsList.length == 0"></el-empty>
		<el-row v-else>
			<el-table v-loading="loading" :data="detailsList" @selection-change="handleSelectionChange" :border="true" >
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="ID" width="50" align="center">
					<template slot-scope="scope">
						{{ scope.row.id }}
					</template>
				</el-table-column>
				<el-table-column label="路线" align="center" prop="transitPlaces">
					<template slot-scope="scope">
						{{ formatTransitPlaces(scope.row.startLocation, scope.row.endLocation, scope.row.transitPlace) }}
					</template>
				</el-table-column>
				<el-table-column label="时间" align="center" prop="startTime" width="260">
					<template slot-scope="scope">
						{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }} - {{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}
					</template>
				</el-table-column>
				<el-table-column label="可占座数" align="center" prop="remainderSeatNum" width="80" />
				<el-table-column label="已占座数" align="center" prop="reserveSeatNum" width="80" />
				<el-table-column label="用车状态" align="center" prop="useCarStatus" width="80">
					<template slot-scope="scope">
						<dict-tag :options="dict.type.use_car_status" :value="scope.row.useCarStatus" />
					</template>
				</el-table-column>
				<el-table-column label="车辆id" align="center" prop="carId" v-if="false" />
				<el-table-column label="车牌" align="center" prop="licensePlate" width="100" />
				<el-table-column label="司机id" align="center" prop="driverId" v-if="false" />
				<el-table-column label="司机名称" align="center" prop="driverName" width="80" />
			</el-table>
			
			<!-- 详情列表 -->
			<pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
		</el-row>

		<!-- 用车申请对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<el-form-item label="车辆id" prop="carId" v-if="false">
					<el-input v-model="form.carId" placeholder="请输入车辆id" />
				</el-form-item>
				<el-form-item label="车型名称" prop="carName" v-if="false">
					<el-input v-model="form.carName" placeholder="请输入车型名称" />
				</el-form-item>
				<el-form-item label="司机id" prop="driverId" v-if="false">
					<el-input v-model="form.driverId" placeholder="请输入司机id" />
				</el-form-item>
				<el-form-item label="司机名称" prop="driverName" v-if="false">
					<el-input v-model="form.driverName" placeholder="请输入司机名称" />
				</el-form-item>
				<el-form-item label="可用座位数量" prop="remainderSeatNum" v-if="false">
					<el-input v-model="form.remainderSeatNum" placeholder="请输入可用座位数量" />
				</el-form-item>
				<el-form-item label="已使用座位数量" prop="reserveSeatNum" v-if="false">
					<el-input v-model="form.reserveSeatNum" placeholder="请输入已使用座位数量" />
				</el-form-item>
				<el-form-item label="开始地点" prop="startLocation">
					<el-input v-model="form.startLocation" placeholder="请输入开始地点" />
				</el-form-item>
				<el-form-item label="中转地点" prop="transitPlace">
					<el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false"
						@close="handleClose(tag)">
						{{ tag }}
					</el-tag>
					<el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput"
						size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
					</el-input>
					<el-button v-else class="button-new-tag" size="small" @click="showInput">+ 中转地点</el-button>
				</el-form-item>
				<el-form-item label="结束地点" prop="endLocation">
					<el-input v-model="form.endLocation" placeholder="请输入结束地点" />
				</el-form-item>
				<el-form-item label="时间" prop="time">
					<el-date-picker clearable v-model="form.time" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始时间" end-placeholder="结束时间" @change="timeChange">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="占座数" prop="occupaSeatNum">
					<el-input v-model.number="form.occupaSeatNum" placeholder="请输入占座数" />
				</el-form-item>
				<el-form-item label="是否有货物" prop="isGoods">
					<el-select v-model="form.isGoods" placeholder="请选择是否有货物">
						<el-option v-for="dict in dict.type.is_goods" :key="dict.value" :label="dict.label"
							:value="dict.value"></el-option>
					</el-select>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer" style="text-align: center;">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 拼车申请对话框 -->
		<el-dialog :title="title" :visible.sync="openPin" width="80%" append-to-body>
			<el-form ref="form2" :model="form2" :rules="rules" label-width="100px">
				<el-form-item label="车辆id" prop="carId" v-if="false">
					<el-input v-model="form2.carId" placeholder="请输入车辆id" />
				</el-form-item>
				<el-form-item label="车型名称" prop="carName" v-if="false">
					<el-input v-model="form2.carName" placeholder="请输入车型名称" :readonly="true" />
				</el-form-item>
				<el-form-item label="司机id" prop="driverId" v-if="false">
					<el-input v-model="form2.driverId" placeholder="请输入司机id" />
				</el-form-item>
				<el-form-item label="司机名称" prop="driverName" v-if="false">
					<el-input v-model="form2.driverName" placeholder="请输入司机名称" :readonly="true" />
				</el-form-item>
				<el-form-item label="开始地点" prop="startLocationId">
					<el-input v-model="form2.startLocation" placeholder="请输入开始地点" disabled />
				</el-form-item>
				<el-form-item label="结束地点" prop="endLocationId">
					<el-input v-model="form2.endLocation" placeholder="请输入结束地点" disabled />
				</el-form-item>
				<el-form-item label="时间" prop="time">
					<el-date-picker clearable v-model="form2.time" type="datetimerange" value-format="yyyy-MM-dd HH:mm" start-placeholder="开始时间" end-placeholder="结束时间" :readonly="true" :disabled="true">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="占座数" prop="occupaSeatNum">
					<el-input v-model.number="form2.occupaSeatNum" placeholder="请输入占座位数量" />
				</el-form-item>
				
				<el-form-item label="是否有货物" prop="isGoods">
					<el-select v-model="form2.isGoods" placeholder="请选择是否有货物">
						<el-option v-for="dict in dict.type.is_goods" :key="dict.value" :label="dict.label"
							:value="dict.value"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer" style="text-align: center;">
				<el-button type="primary" @click="submitFormPin">确 定</el-button>
				<el-button @click="cancelPin">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		listDetails,
		getDetails,
		addDetails,
		updateDetails,
		addPin,
		placeTreeSelect,
		driverTreeSelect,
		carTreeSelect
	} from '@/api/bpmusecardetails/details'
	import { getList as getDriverList } from '@/api/bpmdriver/driver'
	import { getList as getCarList } from '@/api/bpmcar/car'
	import Treeselect from '@riophae/vue-treeselect'
	import { parseTime } from '@/utils/ruoyi'
	import '@riophae/vue-treeselect/dist/vue-treeselect.css'

	export default {
		name: 'Details',
		dicts: ['is_goods', 'use_car_status', 'is_pin_status'],
		components: {
			Treeselect
		},
		data() {
			return {
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 用车明细表格数据
				detailsList: [],
				// 弹出层标题
				title: '',
				// 是否显示弹出层
				open: false,
				openPin: false,
				
				// 删除标志时间范围
				daterangeStartTime: [],
				// 删除标志时间范围
				daterangeEndTime: [],
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					carName: null,
					driverName: null,
					useCarStatus: null,
					startLocation: null,
					endLocation: null,
					startTime: null,
					endTime: null
				},
				time: '',
				// 表单参数
				form: {},
				form2: {},
				// 表单校验
				rules: {
					startLocation: [
						{ required: true, message: '请输入开始地点', trigger: 'blur' },
					],
					endLocation: [
						{ required: true, message: '请输入结束地点', trigger: 'blur' },
					],
					time: [
						{ required: true, message: '请选择时间', trigger: 'blur' },
						{ validator: this.validateTime, trigger: 'blur' },
					],
					occupaSeatNum: [
						{ required: true, message: '请输入占座数', trigger: 'blur' },
						{ type: 'number', message: '输入的不是有效数字', trigger: 'blur' },
						{ validator: this.validateOccupaSeatNum, trigger: 'blur' }
					],
					occupaSeatNum2: [
						{ required: true, message: '请输入占座数', trigger: 'blur' },
						{ type: 'number', message: '输入的不是有效数字', trigger: 'blur' },
						{ validator: this.validateOccupaSeatNum, trigger: 'blur' }
					],
				},
				dynamicTags: [],
				inputVisible: false,
				inputValue: '',
				transitPlaces: null,
				// 地点树选项
				startPlaceOptions: [], //用于存储从后端获取的树形数据
				endPlaceOptions: [], //用于存储从后端获取的树形数据
				startLocationLabel: null,
				endLocationLabel: null,
				driverOptions: undefined,
				carOptions: [],
				remainderSeatNum: 6, // 可占座数量
				btnHandle: false,
				driverHandle: true,
				vehicleHandle: true,
			}
		},
		created() {
			this.getList()
			this.getdriverTree()
			this.getcarTree()
		},
		methods: {
			/**
			 * 时间改变的事件
			 * @param {Object} e
			 */
			timeChange(e){
				if(e && e.length){
					let startDate = new Date(e[0]);
					startDate.setSeconds(startDate.getSeconds() - 1);
					
					let endDate = new Date(e[1]);
					endDate.setSeconds(endDate.getSeconds() + 1);
					
					let params = {
						startTime: parseTime(startDate),
						endTime: parseTime(endDate),
					};

					getDriverList(params).then(res => {
						if(res.data.length == 0){
							this.driverHandle = false;
							this.btnHandle = true;
							
							this.$message({
								message: '您好！该时间段目前行政车辆已约满，如您有用车需求请联总裁办车辆负责人 13311170016 进行车辆调配！',
								type: 'warning'
							});
						}else{
							this.driverHandle = true;
							this.btnHandle = false;
							
							getCarList(params).then(res => {
								if(res.data.length == 0){
									this.vehicleHandle = false;
									this.btnHandle = true;
									
									this.$message({
										message: '您好！该时间段目前行政车辆已约满，如您有用车需求请联总裁办车辆负责人 13311170016 进行车辆调配！',
										type: 'warning'
									});
								}else{
									this.vehicleHandle = true;
									this.btnHandle = false;
								}
							});
						}
					});
				}else{
					this.driverHandle = true;
					this.vehicleHandle = true;
					this.btnHandle = false;
				}
			},
			/**
			 * @param {Object} e
			 */
			changeStartLocation(e){
				console.log('地址改变' , e , this.form2.startLocationId);
			},
			/**
			 * 验证占座数量
			 * @param {Object} rule
			 * @param {Object} value
			 * @param {Object} callback
			 */
			validateOccupaSeatNum(rule, value, callback){
				if (value < 1 || value > this.remainderSeatNum) {
					callback(new Error(`数值必须在1到${this.remainderSeatNum}之间`));
				} else {
					callback();
				}
			},
			/**
			 * 验证时间
			 * @param {Object} rule
			 * @param {Object} value
			 * @param {Object} callback
			 */
			validateTime(rule, value, callback){
				if(new Date(value[0]) < new Date()){
					callback(new Error(`开始时间不可以小于当前时间`));
				}else{
					callback();
				}
			},
			/**
			 * 拼车
			 */
			handlPin(){
				if(this.ids.length == 0){
					this.$message({
						message: '请先选择一条拼车的数据',
						type: 'warning'
					});
				}else if(this.ids.length > 1){
					this.$message({
						message: '只能选择一条拼车的数据',
						type: 'warning'
					});
				}else{
					this.handlePin({id: this.ids[0]});
				}
			},
			/**
			 * 查询可拼车明细列表
			 */
			getList() {
				this.loading = true
				this.queryParams.params = {}
				if (null != this.daterangeStartTime && '' != this.daterangeStartTime) {
					this.queryParams.params['beginStartTime'] = this.daterangeStartTime[0]
					this.queryParams.params['endStartTime'] = this.daterangeStartTime[1]
				}
				if (null != this.daterangeEndTime && '' != this.daterangeEndTime) {
					this.queryParams.params['beginEndTime'] = this.daterangeEndTime[0]
					this.queryParams.params['endEndTime'] = this.daterangeEndTime[1]
				}
				
				console.log();
				
				this.queryParams.isPinStatus = 1;
				listDetails(this.queryParams).then(response => {
					this.detailsList = response.rows || [];
					this.total = response.total
					this.loading = false
				})
			},
			// 取消按钮
			cancel() {
				this.open = false
				this.reset()
				this.clearTags()
				this.daterangeStartTime = []
			},
			cancelPin() {
				this.openPin = false
				this.reset()
				this.clearTags()
			},
			/**
			 * 表单重置
			 */
			reset() {
				this.form = this.initFormData();
				this.form2 = this.initFormData();
				this.resetForm('form');
				this.resetForm('form2');
			},
			/**
			 * 初始化表单数据
			 */
			initFormData(){
				return {
					id: null,
					carId: null,
					carName: null,
					driverId: null,
					driverName: null,
					useCarStatus: null,
					remainderSeatNum: null,
					reserveSeatNum: null,
					startLocation: null,
					endLocation: null,
					time: [],
					startTime: null,
					endTime: null,
					occupaSeatNum: 1,
					isGoods: '0',
					delFlag: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null
				};
			},
			/**
			 * 搜索按钮操作
			 */
			handleQuery() {
				this.queryParams.pageNum = 1
				this.getList()
			},
			/**
			 * 重置按钮操作
			 */
			resetQuery() {
				this.daterangeStartTime = []
				this.daterangeEndTime = []
				this.resetForm('queryForm')
				this.handleQuery()
			},
			/**
			 * 多选框选中数据
			 * @param {Object} selection
			 */
			handleSelectionChange(selection) {
				console.log('多选框选中数据' , selection);
				this.ids = selection.map(item => item.id);
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},

			/**
			 * 拼车按钮操作
			 * @param {Object} row
			 */
			handlePin(row) {
				this.reset();
				
				const id = row.id || this.ids
				getDetails(id).then(response => {
					console.log('getDetails' , response)
					response.data.time = [response.data.startTime, response.data.endTime];
					this.form2 = response.data;
					this.form2.isGoods = '0';
					this.form2.occupaSeatNum = 1;
					this.remainderSeatNum = parseInt(this.form2.remainderSeatNum);
					
					this.openPin = true
					this.title = '拼车申请'
				})
			},

			/** 修改按钮操作 */
			handleUp(row) {
				this.reset()
				const id = row.id || this.ids
				getDetails(id).then(response => {
					this.form = response.data
					this.openUp = true
					this.title = '修改申请'
				})
			},

			/** 新增按钮操作 */
			handleAdd() {
				this.reset()
				this.open = true
				this.title = '用车申请'
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset()
				const id = row.id || this.ids
				getDetails(id).then(response => {
					this.form = response.data;
					this.form.time = [this.form.startTime, this.form.endTime];
					this.form.isGoods = '0';
					
					this.handleClickStartLocation(id);
					this.handleClickEndLocation(id);
					
					this.open = true
					this.title = '修改用车明细'
				})
			},
			/**
			 * 约车提交
			 */
			submitForm() {
				this.$refs['form'].validate(valid => {
					if (valid) {
						this.form.startTime = this.form.time[0];
						this.form.endTime = this.form.time[1];
						let params = this.filterateForm(this.form);
						
						if(!this.driverHandle || !this.vehicleHandle){
							this.$message({
								message: '您好！该时间段目前行政车辆已约满，如您有用车需求请联总裁办车辆负责人 13311170016 进行车辆调配！',
								type: 'warning'
							});
						}
						
						if(!this.btnHandle){
							this.btnHandle = true;
							
							if (this.form.id) {
								updateDetails(params).then(() => {
									this.btnHandle = false;
									this.open = false;
									
									this.$modal.msgSuccess('修改成功！');
									this.getList()
								}).catch(err => {
									this.btnHandle = false;
									console.log('错误' , err);
								});
							} else {
								addDetails(params).then(() => {
									this.btnHandle = false;
									this.open = false;
									
									this.$modal.msgSuccess('约车成功，请等待审批结果！');
									this.getList();
								}).catch(err => {
									this.btnHandle = false;
									console.log('错误' , err);
								});
							}
						}
						
						this.clearTags()
					}
				})
			},
			/**
			 * 拼车提交
			 */
			submitFormPin() {
				this.$refs['form2'].validate(valid => {
					if (valid) {
						let params = {
							id: this.form2.id,
							occupaSeatNum: this.form2.occupaSeatNum,
							startLocationLabel: this.form2.startLocation,
							endLocationLabel: this.form2.endLocation,
							isGoods: this.form2.isGoods
						};
						
						if(!this.btnHandle){
							this.btnHandle = true;
							addPin(params).then(() => {
								this.btnHandle = false;
								this.openPin = false;
								
								this.$modal.msgSuccess('拼车成功')
								this.getList()
							}).catch(err => {
								this.btnHandle = false;
								console.log('错误' , err);
							});
						}
						
						this.clearTags()
						this.daterangeStartTime = [];
					}
				})
			},
			/**
			 * 过滤表单数据
			 * @param {Object} form
			 */
			filterateForm(form){
				let result = {};
				for(let i in form){
					if(form[i] != null && i != 'time'){
						result[i] = form[i];
					}
				}

				return result;
			},
			handleClose(tag) {
				this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
			},
			showInput() {
				this.inputVisible = true
				this.$nextTick(() => {
					this.$refs.saveTagInput.$refs.input.focus()
				})
			},
			handleInputConfirm() {
				let inputValue = this.inputValue
				if (inputValue && this.dynamicTags.length < 9) { // 假设限制输入个数为3个
					this.dynamicTags.push(inputValue)
				}
				this.inputVisible = false
				this.inputValue = ''
				this.form.transitPlace = this.dynamicTags
			},

			clearTags() {
				this.dynamicTags = []
			},
			formatTransitPlaces(startLocation, endLocation, transitPlaces) {
				let address = [startLocation];
				if(transitPlaces) address = address.concat(transitPlaces);
				address.push(endLocation);
				
				return address.join(' - ')
			},
			/**
			 * 获取地点
			 * @param {Object} id
			 */
			getLocation(id) {
				this.endPlaceOptions = [{id:0, label: this.form2.startLocation}];
				if(this.form2.transitPlace){
					this.form2.transitPlace.forEach((item, index) => {
						this.endPlaceOptions.push({id:index + 1, label: item});
					})
				}
				
				this.endPlaceOptions.push({id:this.endPlaceOptions.length, label: this.form2.endLocation});
				this.form2.startLocationId = 0;
				this.form2.endLocationId = this.endPlaceOptions.length - 1;
				
				console.log('获取地点' , this.endPlaceOptions);
			},
			/** 查询开始地点下拉树结构 */
			getPlaceTree(detailsCarId) {
				return placeTreeSelect(detailsCarId).then(response => {
					return response
				}).catch(error => {
					throw error
				})
			},
			/**
			 * 查询司机下拉树结构
			 */
			getdriverTree() {
				driverTreeSelect().then(response => {
					this.driverOptions = response.data
				})
			},

			/**
			 * 查询车辆下拉树结构
			 */
			getcarTree() {
				carTreeSelect().then(response => {
					this.carOptions = response.data
				})
			}

		}
	}
</script>

<style>
	.el-tag+.el-tag {
		margin-left: 10px;
	}

	.button-new-tag {
		margin-left: 10px;
		height: 32px;
		line-height: 30px;
		padding-top: 0;
		padding-bottom: 0;
	}

	.input-new-tag {
		width: 90px;
		margin-left: 10px;
		vertical-align: bottom;
	}
</style>